package com.whiteape.book.ui.fragment;

import android.app.Activity;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.view.View;
import android.widget.CheckBox;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.SeekBar;
import android.widget.TextView;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AlertDialog;
import androidx.core.content.ContextCompat;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.hwangjr.rxbus.annotation.Subscribe;
import com.hwangjr.rxbus.annotation.Tag;
import com.hwangjr.rxbus.thread.EventThread;
import com.whiteape.book.R;
import com.whiteape.book.common.RxEvent;
import com.whiteape.book.core.manager.ReadSettingManager;
import com.whiteape.book.core.page.PageLoader;
import com.whiteape.book.core.page.PageMode;
import com.whiteape.book.core.page.PageStyle;
import com.whiteape.book.core.page.PageStyleNew;
import com.whiteape.book.core.page.PageTextIntervalMode;
import com.whiteape.book.ui.activity.BookReadActivity;
import com.whiteape.book.ui.activity.TypefaceManagerActivity;
import com.whiteape.book.ui.adapter.ReadSettingColorStyleAdapter;
import com.whiteape.book.ui.base.BaseFragment;
import com.whiteape.book.ui.dialog.NovelBackgroundDialogFragment;
import com.whiteape.book.utils.BrightnessUtils;
import com.whiteape.book.utils.ToastUtils;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;

public class ReadSettingCommonFragment extends BaseFragment {

    @BindView(R.id.read_setting_iv_brightness_minus)
    ImageView mIvBrightnessMinus;
    @BindView(R.id.read_setting_sb_brightness)
    SeekBar mSbBrightness;
    @BindView(R.id.read_setting_iv_brightness_plus)
    ImageView mIvBrightnessPlus;
    @BindView(R.id.read_setting_cb_brightness_auto)
    CheckBox mCbBrightnessAuto;
    @BindView(R.id.read_setting_tv_font_minus)
    TextView mTvFontMinus;
    @BindView(R.id.read_setting_tv_font)
    TextView mTvFont;
    @BindView(R.id.read_setting_tv_font_plus)
    TextView mTvFontPlus;
    //    @BindView(R.id.read_setting_cb_font_default)
//    ImageView mCbFontDefault;
    @BindView(R.id.read_setting_rg_page_mode)
    RadioGroup mRgPageMode;

    @BindView(R.id.read_setting_rb_simulation)
    RadioButton mRbSimulation;
    @BindView(R.id.read_setting_rb_cover)
    RadioButton mRbCover;
    @BindView(R.id.read_setting_rb_slide)
    RadioButton mRbSlide;
    @BindView(R.id.read_setting_rb_scroll)
    RadioButton mRbScroll;
    @BindView(R.id.read_setting_rb_none)
    RadioButton mRbNone;
    @BindView(R.id.read_setting_rv_bg)
    RecyclerView mRvBg;
    //    @BindView(R.id.read_setting_tv_more)
//    TextView mTvMore;
    @BindView(R.id.read_setting_tv_change_typeface)
    ImageView mTvTypeface;

    @BindView(R.id.read_setting_cb_bold)
    CheckBox mCbBold;

    @BindView(R.id.read_setting_tv_font_fanti)
    TextView mTvFontFanJian;

//    @BindView(R.id.read_setting_rb_interval_5)
//    ImageView mIvInterval5;
//    @BindView(R.id.read_setting_rb_interval_4)
//    ImageView mIvInterval4;
//    @BindView(R.id.read_setting_rb_interval_3)
//    ImageView mIvInterval3;

    @BindView(R.id.tv_read_bg_setting_add_colors)
    TextView mTvColorStyleAdd;
    /************************************/
//    private PageStyleAdapter mColorStyleAdapter;
    private ReadSettingColorStyleAdapter mColorStyleAdapter;
    private ReadSettingManager mSettingManager;
    private PageLoader mPageLoader;
    private Activity mActivity;


    private PageMode mPageMode;
    private PageStyleNew mPageStyle;

    private int mBrightness;
    private int mTextSize;

    private boolean isBrightnessAuto;
    private boolean isTextDefault;
    private List<PageStyleNew> pageStyleDataList;

    BookReadSettingListener listener;
    private NovelBackgroundDialogFragment mNovelBackgroundDialogFragment;

    public ReadSettingCommonFragment(/*Activity activity, PageLoader pageLoader*/) {
    }


    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        this.mActivity = getActivity();
        this.mPageLoader = ((BookReadActivity)mActivity).getPageLoader();
        initWidget();
    }

    @Override
    protected int getContentId() {
        return R.layout.dialog_read_setting_common;
    }

    @Override
    protected void initView(Bundle savedInstanceState) {
        super.initView(savedInstanceState);
        setUpAdapter();
    }

    public NovelBackgroundDialogFragment getNovelBackgroundDialogFragment() {
        return mNovelBackgroundDialogFragment;
    }

    private Drawable getDrawable(int drawRes) {
        return ContextCompat.getDrawable(getContext(), drawRes);
    }

    private void initColorsForFirstTime() {
        String bgColorStr = "#CEC29C;#CCEBCC;#AAAAAA;#D1CEC5;#001C27";
        String fgColorStr = "#2C2C2C;#2F332D;#92918C;#383429;#627176";

        ReadSettingManager.getInstance().addReadColors(ReadSettingManager.READ_COLOR_TYPE_BG, bgColorStr);
        ReadSettingManager.getInstance().addReadColors(ReadSettingManager.READ_COLOR_TYPE_FG, fgColorStr);

        String[] bgArr = bgColorStr.split(";");
        String[] fgArr = fgColorStr.split(";");
        List<PageStyleNew> pageStyleNewList = new ArrayList<>();
        for(int i = 0;i<bgArr.length;i++){
            pageStyleNewList.add(new PageStyleNew(bgArr[i],fgArr[i]));
        }
        ReadSettingManager.getInstance().setPageStyleAll(pageStyleNewList);
    }

    private void setUpAdapter() {
        if (!ReadSettingManager.getInstance().isReadColorsInited()){
            initColorsForFirstTime();
            ReadSettingManager.getInstance().setReadColorsInited(true);
        }

        pageStyleDataList = new ArrayList<>();
        mColorStyleAdapter = new ReadSettingColorStyleAdapter(R.layout.item_read_setting_page_colors, pageStyleDataList);
        mRvBg.setLayoutManager(new LinearLayoutManager(getContext(), LinearLayout.HORIZONTAL, false));
        mRvBg.setAdapter(mColorStyleAdapter);
        pageStyleDataList.addAll(ReadSettingManager.getInstance().getPageStyleAll());
        mColorStyleAdapter.setSelected(mPageStyle);

    }

    @Override
    protected void initEvent() {
        super.initEvent();
        initClick();
    }

    public void setListener(BookReadSettingListener listener) {
        this.listener = listener;
    }

    @Override
    protected void initData(Bundle savedInstanceState) {
        super.initData(savedInstanceState);

        mSettingManager = ReadSettingManager.getInstance();

        isBrightnessAuto = mSettingManager.isBrightnessAuto();
        mBrightness = mSettingManager.getBrightness();
        mTextSize = mSettingManager.getTextSize();
        isTextDefault = mSettingManager.isDefaultTextSize();
        mPageMode = mSettingManager.getPageMode();
        mPageStyle = mSettingManager.getPageStyleNew();
    }

    private void initWidget() {
        mNovelBackgroundDialogFragment = new NovelBackgroundDialogFragment(mActivity, mPageLoader);
        mSbBrightness.setProgress(mBrightness);
        mTvFont.setText(mTextSize + "");
        mCbBrightnessAuto.setChecked(isBrightnessAuto);
//        mCbFontDefault.setChecked(isTextDefault);
        loadSettingData();
        initPageMode();
        //RecyclerView
//        setUpAdapter();
//        hideSystemBar();

    }


//    private void setTextInterval(View view) {
//        if (view == mIvInterval3) {
//            mIvInterval3.setImageResource(R.mipmap.ic_itv_light_3);
//            mIvInterval3.setBackgroundResource(R.drawable.shape_btn_read_setting_checked);
//            mIvInterval4.setBackgroundResource(R.drawable.shape_btn_read_setting_normal);
//            mIvInterval4.setImageResource(R.mipmap.ic_itv_4);
//            mIvInterval5.setBackgroundResource(R.drawable.shape_btn_read_setting_normal);
//            mIvInterval5.setImageResource(R.mipmap.ic_itv_5);
//            ReadSettingManager.getInstance().setSharedReadTextInterval(PageTextIntervalMode.MODE_LOOSE);
//            mPageLoader.setTextInterval(PageTextIntervalMode.MODE_LOOSE);
//        } else if (view == mIvInterval4) {
//            mIvInterval4.setImageResource(R.mipmap.ic_itv_light_4);
//            mIvInterval4.setBackgroundResource(R.drawable.shape_btn_read_setting_checked);
//            mIvInterval3.setBackgroundResource(R.drawable.shape_btn_read_setting_normal);
//            mIvInterval3.setImageResource(R.mipmap.ic_itv_3);
//            mIvInterval5.setBackgroundResource(R.drawable.shape_btn_read_setting_normal);
//            mIvInterval5.setImageResource(R.mipmap.ic_itv_5);
//            ReadSettingManager.getInstance().setSharedReadTextInterval(PageTextIntervalMode.MODE_NORMAL);
//            mPageLoader.setTextInterval(PageTextIntervalMode.MODE_NORMAL);
//
//        } else if (view == mIvInterval5) {
//            mIvInterval5.setImageResource(R.mipmap.ic_itv_light_5);
//            mIvInterval5.setBackgroundResource(R.drawable.shape_btn_read_setting_checked);
//            mIvInterval4.setBackgroundResource(R.drawable.shape_btn_read_setting_normal);
//            mIvInterval4.setImageResource(R.mipmap.ic_itv_4);
//            mIvInterval3.setBackgroundResource(R.drawable.shape_btn_read_setting_normal);
//            mIvInterval3.setImageResource(R.mipmap.ic_itv_3);
//            ReadSettingManager.getInstance().setSharedReadTextInterval(PageTextIntervalMode.MODE_TIGHT);
//            mPageLoader.setTextInterval(PageTextIntervalMode.MODE_TIGHT);
//        }
//    }

    private void initClick() {
        //亮度调节
        mIvBrightnessMinus.setOnClickListener(
                (v) -> {
                    if (mCbBrightnessAuto.isChecked()) {
                        mCbBrightnessAuto.setChecked(false);
                    }
                    int progress = mSbBrightness.getProgress() - 1;
                    if (progress < 0) return;
                    mSbBrightness.setProgress(progress);
                    BrightnessUtils.setBrightness(mActivity, progress);
                }
        );
        mIvBrightnessPlus.setOnClickListener(
                (v) -> {
                    if (mCbBrightnessAuto.isChecked()) {
                        mCbBrightnessAuto.setChecked(false);
                    }
                    int progress = mSbBrightness.getProgress() + 1;
                    if (progress > mSbBrightness.getMax()) return;
                    mSbBrightness.setProgress(progress);
                    BrightnessUtils.setBrightness(mActivity, progress);
                    //设置进度
                    ReadSettingManager.getInstance().setBrightness(progress);
                }
        );

        mSbBrightness.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {

            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {

            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {
                int progress = seekBar.getProgress();
                if (mCbBrightnessAuto.isChecked()) {
                    mCbBrightnessAuto.setChecked(false);
                }
                //设置当前 Activity 的亮度
                BrightnessUtils.setBrightness(mActivity, progress);
                //存储亮度的进度条
                ReadSettingManager.getInstance().setBrightness(progress);
            }
        });

        mCbBrightnessAuto.setOnCheckedChangeListener(
                (buttonView, isChecked) -> {
                    if (isChecked) {
                        //获取屏幕的亮度
                        BrightnessUtils.setBrightness(mActivity, BrightnessUtils.getScreenBrightness(mActivity));
                    } else {
                        //获取进度条的亮度
                        BrightnessUtils.setBrightness(mActivity, mSbBrightness.getProgress());
                    }
                    ReadSettingManager.getInstance().setAutoBrightness(isChecked);
                }
        );

        //字体大小调节
        mTvFontMinus.setOnClickListener(
                (v) -> {
//                    if (mCbFontDefault.isChecked()) {
//                        mCbFontDefault.setChecked(false);
//                    }
                    int fontSize = Integer.valueOf(mTvFont.getText().toString()) - 1;
                    if (fontSize < 0) return;
                    mTvFont.setText(fontSize + "");
                    mPageLoader.setTextSize(fontSize);
                }
        );

        mTvFontPlus.setOnClickListener(
                (v) -> {
//                    if (mCbFontDefault.isChecked()) {
//                        mCbFontDefault.setChecked(false);
//                    }
                    int fontSize = Integer.valueOf(mTvFont.getText().toString()) + 1;
                    mTvFont.setText(fontSize + "");
                    mPageLoader.setTextSize(fontSize);
                }
        );


//        mCbFontDefault.setOnCheckedChangeListener(
//                (buttonView, isChecked) -> {
//                    if (isChecked) {
//                        int fontSize = ScreenUtils.dpToPx(DEFAULT_TEXT_SIZE);
//                        mTvFont.setText(fontSize + "");
//                        mPageLoader.setTextSize(fontSize);
//                    }
//                }
//        );

        //Page Mode 切换
        mRgPageMode.setOnCheckedChangeListener(
                (group, checkedId) -> {
                    for (int i = 0; i < mRgPageMode.getChildCount(); i++) {
                        RadioButton radioButton = (RadioButton) mRgPageMode.getChildAt(i);
                        if (radioButton.getId() == checkedId) {
                            radioButton.setTextColor(ContextCompat.getColor(mActivity, R.color.orange));
                        } else {
                            radioButton.setTextColor(ContextCompat.getColor(mActivity, R.color.read_menu_text));
                        }
                    }
                    PageMode pageMode;
                    switch (checkedId) {
                        case R.id.read_setting_rb_simulation:
                            pageMode = PageMode.SIMULATION;
                            break;
                        case R.id.read_setting_rb_cover:
                            pageMode = PageMode.COVER;
                            break;
                        case R.id.read_setting_rb_slide:
                            pageMode = PageMode.SLIDE;
                            break;
                        case R.id.read_setting_rb_scroll:
                            pageMode = PageMode.SCROLL;
                            break;
                        case R.id.read_setting_rb_none:
                            pageMode = PageMode.NONE;
                            break;
                        default:
                            pageMode = PageMode.SIMULATION;
                            break;
                    }
                    mPageLoader.setPageMode(pageMode);
                }
        );

        //背景的点击事件
        mColorStyleAdapter.setOnItemClickListener(
                (adapter, view, pos) -> {
//                    SystemBarUtils.setNavigationBarColor(mActivity, ContextCompat.getColor(mActivity, PageStyle.values()[pos].getBgColor()));
                    if(mPageLoader!= null && ReadSettingManager.getInstance().isNightMode()){
                        ToastUtils.show("夜间模式下无法选择背景");
                        return;
                    }
                    PageStyleNew pageStyleNew = pageStyleDataList.get(pos);
                    mColorStyleAdapter.setSelected(pageStyleNew);
                    mPageLoader.setPageStyle(pageStyleNew);
                    mColorStyleAdapter.notifyDataSetChanged();
                    ReadSettingManager.getInstance().setPageStyleNew(pageStyleNew);
                    if (listener != null) {
                        listener.onPageStyleChanged(PageStyle.values()[pos]);
                    }

                }

        );
        mColorStyleAdapter.setOnItemLongClickListener((adapter, view, position) -> {
            if(pageStyleDataList.get(position).equals(mColorStyleAdapter.getSelected())){
                ToastUtils.show("不能删除当前使用的配色方案");
                return true;
            }
            new AlertDialog.Builder(mActivity)
                    .setTitle("提示")
                    .setMessage("确认删除此配色方案？")
                    .setNegativeButton("取消",(dialog, which) -> {

                    })
                    .setPositiveButton("确认",(dialog, which) -> {
                        PageStyleNew pageStyleNew = pageStyleDataList.get(position);
                        String bgColor = pageStyleNew.getBgColor();
                        if(!bgColor.startsWith("#")){
                            File bg = new File(bgColor);
                            if(bg.exists()){
                                bg.delete();
                            }
                        }
                        pageStyleDataList.remove(position);
                        mColorStyleAdapter.notifyDataSetChanged();
                        //TODO 删掉背景图
                        ReadSettingManager.getInstance().setPageStyleAll(pageStyleDataList);

                    }).show();
            return true;
        });

        mTvColorStyleAdd.setOnClickListener(v -> {

            if(mNovelBackgroundDialogFragment !=null &&
            !mNovelBackgroundDialogFragment.isAdded() &&
                    !mNovelBackgroundDialogFragment.isVisible() &&
                    !mNovelBackgroundDialogFragment.isRemoving()

            ) {
                mNovelBackgroundDialogFragment.show(getChildFragmentManager(), "xxx");
            }
        });

        mTvTypeface.setOnClickListener(
                (view -> {
                    Intent intent = new Intent(getContext(), TypefaceManagerActivity.class);
                    mActivity.startActivityForResult(intent, BookReadActivity.REQUEST_CHANGE_TYPEFACE);
                    //关闭当前设置
//                     dismiss();

                })
        );

        mCbBold.setOnCheckedChangeListener((buttonView, isChecked) -> {
            ReadSettingManager.getInstance().setBold(isChecked);
            mPageLoader.setBold(isChecked);
        });

        mTvFontFanJian.setOnClickListener(v -> {
            //繁体简体
            boolean isFanti = ReadSettingManager.getInstance().getFanti();
            isFanti = !isFanti;
            ReadSettingManager.getInstance().setFanti(isFanti);
            if (isFanti) {
                mTvFontFanJian.setText("简");
            } else {
                mTvFontFanJian.setText("繁");
            }
            mPageLoader.reDrawCurPage(true);

        });

//        mIvInterval3.setOnClickListener(v -> {
//            setTextInterval(mIvInterval3);
//        });
//        mIvInterval4.setOnClickListener(v -> {
//            setTextInterval(mIvInterval4);
//        });
//        mIvInterval5.setOnClickListener(v -> {
//            setTextInterval(mIvInterval5);
//        });
    }

    public boolean isBrightFollowSystem() {
        if (mCbBrightnessAuto == null) {
            return false;
        }
        return mCbBrightnessAuto.isChecked();
    }

    public interface BookReadSettingListener {
        void onPageStyleChanged(PageStyle pageStyle);
    }

    private void initPageMode() {
        switch (mPageMode) {
            case SIMULATION:
                mRbSimulation.setChecked(true);
                break;
            case COVER:
                mRbCover.setChecked(true);
                break;
            case SLIDE:
                mRbSlide.setChecked(true);
                break;
            case NONE:
                mRbNone.setChecked(true);
                break;
            case SCROLL:
                mRbScroll.setChecked(true);
                break;
        }
    }

    private void loadSettingData() {
        mCbBold.setChecked(ReadSettingManager.getInstance().getBold());
//        int textInterval = ReadSettingManager.getInstance().getReadTextInterval();
//        if (textInterval == PageTextIntervalMode.MODE_LOOSE) {
//            setTextInterval(mIvInterval3);
//        } else if (textInterval == PageTextIntervalMode.MODE_NORMAL) {
//            setTextInterval(mIvInterval4);
//        } else if (textInterval == PageTextIntervalMode.MODE_TIGHT) {
//            setTextInterval(mIvInterval5);
//        }
        mTvFontFanJian.setText(ReadSettingManager.getInstance().getFanti() ? "简" : "繁");
    }


    /**
     * 当page style编辑 （新增或者减少之后） 发出消息
     */
    @Subscribe(thread = EventThread.MAIN_THREAD, tags = {@Tag(RxEvent.READ_PAGE_STYLE_CHANGED)})
    public void onPageStyleChanged(PageStyleNew pageStyleNew) {
        if(mColorStyleAdapter != null) {
//            pageStyleDataList.clear();
//            pageStyleDataList.addAll(ReadSettingManager.getInstance().getPageStyleAll());
            if(!pageStyleDataList.contains(pageStyleNew)){
                pageStyleDataList.add(pageStyleNew);
            }
            mColorStyleAdapter.setSelected(pageStyleNew);
            mColorStyleAdapter.notifyDataSetChanged();
        }

    }

}
